//
//  ISSafetyAlarmMailManager.m
//  iPhoneSafety
//
//  Created by dl on 2019/1/5.
//  Copyright © 2019 com.li.ding. All rights reserved.
//

#import "ISSafetyAlarmMailManager.h"
#import "SKPSMTPMessage.h"
#import <CoreLocation/CoreLocation.h>
#import "NSData+Base64Additions.h"
#import "AppDelegate.h"

NSString * const kISSafetyAlarmMailReceiver = @"kISSafetyAlarmMailReceiver";
NSString * const kISSafetyAlarmMailReceiverOn = @"kISSafetyAlarmMailReceiverOn";

NSString * const kISSafetyAlarmAuthLocationNotification = @"kISSafetyAlarmAuthLocationNotification";

typedef void (^MailSendLocationCompletion) (NSString *locationStr);

@interface ISSafetyAlarmMailManager()<SKPSMTPMessageDelegate, CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager* locationManager;
@property (strong,nonatomic) CLGeocoder *geocoder;

@property (nonatomic, copy, readwrite) NSString *receiver;
@end

@implementation ISSafetyAlarmMailManager

NW_SINGLETON_INSTANCE_METHOD_IMPLEMENTATION

- (instancetype)init {
    self = [super init];
    if (self) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        self.geocoder = [[CLGeocoder alloc] init];

        self.fromEmail = @"15990043752@163.com";
        self.loginAccount = @"15990043752@163.com";
        self.loginPassword = @"Ping211314";
        self.relayHost = @"smtp.163.com";
        
        self.receiver = [[NSUserDefaults standardUserDefaults] valueForKey:kISSafetyAlarmMailReceiver];
    }
    return self;
}

- (void) requestLocationAuthorization {
    [self.locationManager requestAlwaysAuthorization];
    [self.locationManager requestWhenInUseAuthorization];
}

- (void) enableTakePhoto:(BOOL)enable {
    [[NSUserDefaults standardUserDefaults] setBool:enable forKey:kISSafetyAlarmMailReceiverOn];
}

- (BOOL)isTakePhotoOn {
    return [[NSUserDefaults standardUserDefaults] boolForKey:kISSafetyAlarmMailReceiverOn];
}

- (void) updateReceiver:(NSString *)receiver {
    self.receiver = receiver;
    [[NSUserDefaults standardUserDefaults] setValue:receiver forKey:kISSafetyAlarmMailReceiver];
}

- (void) sendMailWithmage:(UIImage *)image completion:(MailSendCompletion)completion {
    
    if (!image || [NSString nw_isEmptyString:self.receiver]) {
        !completion ?: completion(NO, nil);
        return ;
    }
    @weakify(self)
    [self _fetchLocationWithCompletion:^(NSString *locationStr) {
        @strongify(self)
        [self _sendMailTo:self.receiver image:image location:locationStr completion:completion];
    }];
}

static void *MailSendLocationCompletionKey = &MailSendLocationCompletionKey;
- (void) _fetchLocationWithCompletion:(MailSendLocationCompletion)completion {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status != kCLAuthorizationStatusAuthorizedAlways && status != kCLAuthorizationStatusAuthorizedWhenInUse) {
        !completion ?: completion(nil);
    } else {
        [self.locationManager startUpdatingLocation];
        [self.locationManager bk_associateValue:completion withKey:MailSendLocationCompletionKey];
    }
}

static void *MailSendCompletionKey = &MailSendCompletionKey;

- (void) _sendMailTo:(NSString *)receiver image:(UIImage *)image location:(NSString *)location completion:(MailSendCompletion)completion {
    SKPSMTPMessage *myMessage = [[SKPSMTPMessage alloc] init];
    myMessage.fromEmail = self.fromEmail;
    myMessage.toEmail = receiver;
//    myMessage.bccEmail = @"ocsh@qq.com";
    myMessage.relayHost = self.relayHost;

    myMessage.requiresAuth=YES;
    if (myMessage.requiresAuth) {
        myMessage.login = self.loginAccount;
        myMessage.pass = self.loginPassword;
    }
    myMessage.wantsSecure = YES;
    myMessage.subject = @"【不敢碰】疑似小偷照片";
    myMessage.delegate = self;
    
    NSMutableArray *parts = [NSMutableArray array];
    
    if (image) {
        NSString *imageFile = @"attachment;\r\n\tfilename=\"pic.jpeg\"";
        NSString *imgDataBase64 = [UIImageJPEGRepresentation(image, 0.3) encodeBase64ForData];
        NSDictionary *imagePart = @{kSKPSMTPPartContentTypeKey: @"image/jpg;\r\n\tx-unix-mode=0644;\r\n\tname=\"可疑人照片.jpg\"",
                                    kSKPSMTPPartContentDispositionKey: imageFile,
                                    kSKPSMTPPartMessageKey: imgDataBase64,
                                    kSKPSMTPPartContentTransferEncodingKey: @"base64"
                                    };
        [parts addObject:imagePart];
    }
    
    NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
    [dateformate setDateFormat:@"时间: yyyy年MM月dd日 HH时mm分ss秒"];
    NSString *dateStr = [dateformate stringFromDate:[NSDate date]];
    NSDictionary *timeInfoPart = @{kSKPSMTPPartContentTypeKey: @"text/plain; charset=UTF-8",
                                   kSKPSMTPPartMessageKey: dateStr,
                                   kSKPSMTPPartContentTransferEncodingKey: @"8bit"};
    [parts addObject:timeInfoPart];
    
    if ([NSString nw_isNotEmptyString:location]) {
        NSDictionary *locationInfoPart = @{kSKPSMTPPartContentTypeKey: @"text/plain; charset=UTF-8",
                                           kSKPSMTPPartMessageKey: [NSString stringWithFormat:@"位置: %@", location],
                                           kSKPSMTPPartContentTransferEncodingKey: @"8bit"};
        [parts addObject:locationInfoPart];
    }
    
    myMessage.parts = parts;
    [myMessage send];
    [myMessage bk_associateValue:completion withKey:MailSendCompletionKey];
}

#pragma mark - SKPSMTPMessageDelegate
-(void)messageSent:(SKPSMTPMessage *)message {
    MailSendCompletion completion = [message bk_associatedValueForKey:MailSendCompletionKey];
    !completion ?: completion(YES, nil);
}

-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error {
    MailSendCompletion completion = [message bk_associatedValueForKey:MailSendCompletionKey];
    !completion ?: completion(NO, error);
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coordinate = location.coordinate;
    NSLog(@"纬度:%f 经度:%f", coordinate.latitude, coordinate.longitude);
    
    [manager stopUpdatingLocation];
    
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *place = placemarks.firstObject;
        NSDictionary *addressDetailDict = place.addressDictionary;
        NSString *locationStr = [NSString stringWithFormat:@"%@%@%@ %@%@%@",
                                 addressDetailDict[@"Country"],
                                 addressDetailDict[@"State"],
                                 addressDetailDict[@"City"],
                                 addressDetailDict[@"SubLocality"],
                                 addressDetailDict[@"Thoroughfare"],
                                 addressDetailDict[@"Street"]];
        
        MailSendLocationCompletion completion = [manager bk_associatedValueForKey:MailSendLocationCompletionKey];
        !completion ?: completion(locationStr);
    }];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:kISSafetyAlarmAuthLocationNotification object:@(status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse)];
    });
}

@end
